package com.newtype.meeting.server.service;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.newtype.meeting.client.model.Account;
import com.newtype.meeting.client.model.Department;
import com.newtype.meeting.client.service.DepartmentService;
import com.newtype.meeting.server.PMF;
import com.newtype.meeting.shared.AccountTreeDTO;
import com.newtype.meeting.shared.DepartmentTreeDTO;

/**
 * 部门业务逻辑方法实现类
 * @author 汪恭泽
 * Jun 1, 2011 2:21:02 PM
 */
@SuppressWarnings("serial")
public class DepartmentServiceImpl extends RemoteServiceServlet implements
		DepartmentService {
	/** 保存部门信息 */
	@Override
	public void saveDepartment(Department department) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(department);
		} finally {
			pm.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Department> getDepartmentChildren(Department department) {
		List<Department> depts = new ArrayList<Department>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Department> results = null;
		try {
			if (department != null) {
				Query query = pm.newQuery(Department.class,
						"parentDeptID == paramID");
				query.declareParameters("String paramID");
				results = (List<Department>) query.execute(department.getId());
			} else {
				Query query = pm.newQuery(Department.class,
						"parentDeptID == null");
				results = (List<Department>) query.execute();
			}
			depts = (List<Department>) pm.detachCopyAll(results);
			for (Department dept : depts) {
				dept.updateProperties();
			}
		} finally {
			pm.close();
		}
		return depts;
	}

	/** 下级部门列表 */
	@SuppressWarnings("unchecked")
	public List<DepartmentTreeDTO> listChildDepartment(
			DepartmentTreeDTO department) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<DepartmentTreeDTO> toReturn = new ArrayList<DepartmentTreeDTO>();
		List<Department> result = null;
		try {
			Query query = pm.newQuery(Department.class,
					"parentDeptID == paramID");
			query.declareParameters("String paramID");
			result = (List<Department>) query.execute(department.getId());
			for (Department d : result) {
				toReturn.add(d.toLightTreeDTO());
			}
		} finally {
			pm.close();
		}
		return toReturn;
	}

	/** 一级部门列表 */
	@SuppressWarnings("unchecked")
	public List<DepartmentTreeDTO> listDepartment() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<DepartmentTreeDTO> toReturn = new ArrayList<DepartmentTreeDTO>();
		List<Department> result = null;
		try {
			Query query = pm.newQuery(Department.class, "parentDeptID == null");
			result = (List<Department>) query.execute();
			for (Department d : result) {
				toReturn.add(d.toLightTreeDTO());
			}
		} finally {
			pm.close();
		}
		return toReturn;
	}

	/**
	 * 获得组织结构(包括部门和人员)
	 */
	public DepartmentTreeDTO getTreeModel() {
		List<DepartmentTreeDTO> dts = getAllDepartments();
		DepartmentTreeDTO root = new DepartmentTreeDTO(null, "ROOT");
		for (int i = 0; i < dts.size(); i++) {
			root.add(dts.get(i));
		}
		return root;
	}

	/**
	 * 获取部门组织结构
	 */
	public DepartmentTreeDTO getDepartmentTree() {
		List<DepartmentTreeDTO> dts = getAllDepartment();
		DepartmentTreeDTO root = new DepartmentTreeDTO(null, "ROOT");
		for (int i = 0; i < dts.size(); i++) {
			root.add(dts.get(i));
		}
		return root;
	}

	/**
	 * 根据部门ID返回该部门的所有人员
	 * @param deptId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<AccountTreeDTO> getAccountsByDeptID(String deptId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<AccountTreeDTO> toReturn = new ArrayList<AccountTreeDTO>();
		try {
			Query query = pm.newQuery(Account.class, "deptID == keyword");
			query.declareParameters("String keyword");
			List<Account> result = (List<Account>) query.execute(deptId);
			for (Account a : result) {
				Department department=getDepartment(a.getDeptID());		
				toReturn.add(a.toLightTreeDTO(department));
			}
		} finally {
			pm.close();
		}
		return toReturn;
	}

	/**
	 * 设置部门和人员
	 * @param d
	 */
	private void setChildren(DepartmentTreeDTO d) {
		//获取下级部门集合
		List<DepartmentTreeDTO> allChildren = listChildDepartment(d);
		List<AccountTreeDTO> atds = getAccountsByDeptID(d.getId());
		if (atds != null && atds.size() > 0) {
			d.setAccountChildren(atds);
		}
		if (allChildren != null && allChildren.size() > 0) {
			d.setDepartmentChildren(allChildren);
			for (DepartmentTreeDTO dt : allChildren) {
				setChildren(dt);
			}
		}
	}

	/**
	 * 设置部门
	 * @param dto
	 */
	private void setDepartmentChildren(DepartmentTreeDTO dto) {
		//获取下级部门集合
		List<DepartmentTreeDTO> allChildren = listChildDepartment(dto);
		if (allChildren != null && allChildren.size() > 0) {
			dto.setDepartmentChildren(allChildren);
			for (DepartmentTreeDTO dt : allChildren) {
				setDepartmentChildren(dt);
			}
		}
	}

	/**
	 * 获取组织结构（包括部门和人员）
	 * @return
	 */
	public List<DepartmentTreeDTO> getAllDepartments() {
		//获取一级部门集合
		List<DepartmentTreeDTO> dtList = listDepartment();
		for (DepartmentTreeDTO dt : dtList) {
			setChildren(dt);
		}
		return dtList;
	}

	/**
	 * 获取部门组织结构
	 * @return
	 */
	private List<DepartmentTreeDTO> getAllDepartment() {
		//获取一级部门集合
		List<DepartmentTreeDTO> dtList = listDepartment();
		for (DepartmentTreeDTO dt : dtList) {
			setDepartmentChildren(dt);
		}
		return dtList;
	}

	/**
	 * 根据ID返回部门信息
	 */
	public Department getDepartment(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		return pm.getObjectById(Department.class, id);
	}

}
